package io.xxx.walle.task;

import io.xxx.walle.room.Room;
import io.xxx.walle.wechaty.PushResult;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class TaskPushRecordService {

    @Resource
    private TaskPushRecordRepository pushRecordRepository;

    @Resource
    private TaskPushRecordEntryRepository pushRecordEntryRepository;

    @Transactional
    public void addTaskPushRecord(Task task, Room room, PushResult pushResult) {
        LocalDateTime now = LocalDateTime.now();

        TaskPushRecord record = new TaskPushRecord();
        record.setTask(task);
        record.setRoom(room);
        record.setCreatedTime(now);
        record.setPayloadCount(task.getPayloads().size());
        record.setPushStartTime(pushResult.getPushStartTime());
        record.setPushEndTime(pushResult.getPushEndTime());
        record.setFailedCount(pushResult.getFailedPayloads().size());

        List<TaskPushRecordEntry> recordEntries = task.getPayloads()
                .stream()
                .map(payload -> {
                    TaskPushRecordEntry entry = new TaskPushRecordEntry();
                    entry.setTask(task);
                    entry.setRoom(room);
                    entry.setCreatedTime(now);
                    entry.setPayloadType(payload.getType());
                    entry.setPayloadMiniProgramType(payload.getMiniProgramType());
                    entry.setPayload(payload);
                    return entry;
                })
                .toList();

        pushRecordRepository.save(record);
        pushRecordEntryRepository.saveAll(recordEntries);
    }
}
